package com.ecity.util 
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.utils.setInterval;
	import flash.utils.Timer;
	
	/**
	 * ...
	 * @author yicheng.zhang
	 */
	public class BitmapClip extends Sprite {
		private var timer:Timer;
		public var _fps:int;
		public var _currentFrame:int;
		public var _totalFrame:int;
		private var _picmap:HashMap;
		private var _keyWord:String;
		private var canvas:Sprite;
		private var playable:Boolean;
		private var _idel:Boolean;
		private var _startFrame:int;
		private var _stopFrame:int;
		private var _loop:Boolean;
		
		public function BitmapClip(name:String, fps:int = 25, autoplay:Boolean = true) {
			this.name = name;
			_picmap = UIFactory.uimap;
			_keyWord = name + "_";
			_fps = fps;
			playable = autoplay;
			canvas = new Sprite();
			this.addChild(canvas);
			_startFrame = 1;
			_currentFrame = 1;
			_totalFrame = 0;
			_idel = true;
			checkWord(_picmap);
		}
		
		private function checkWord(picmap:HashMap):void{
			picmap.eachKey(getMachValue);
		}
		
		private function getMachValue():void {
			var reg:RegExp = new RegExp(_keyWord,"gi");
			if (reg.test(arguments[0])) {
				_totalFrame++;
			}
		}

		private function draw():void {
			var bitmap:Bitmap = _picmap.get(_keyWord + _currentFrame) as Bitmap;
			var bmd:BitmapData = bitmap.bitmapData;
			this.width = bitmap.width;
			this.height = bitmap.height;
			canvas.graphics.clear();
			canvas.graphics.beginBitmapFill(bmd);
			canvas.graphics.drawRect(0, 0, bitmap.width, bitmap.height);
			canvas.graphics.endFill();
		}
			
		public function play():void {
			_currentFrame = 1;
			_stopFrame = this._totalFrame;
			playable = true;
			timerRuning();
		}
		
		private function timerRuning():void {
			timer= new Timer(1000/_fps,1);
			timer.start();
			_idel = false;
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
			draw();
		}
		
		private function onTimerComplete(e:TimerEvent):void {
			_idel = true;
			timer.removeEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
			timer = null;
			if (playable) {
				if (_currentFrame >= _stopFrame) {
					if (_loop) {
						_currentFrame = _startFrame;
					}else {
						playable = false;
					}
				}else {
					_currentFrame++;
				}
				timerRuning();
			}
		}
		 
		public function stop():void {
			playable = false;
			timerRuning();
		}
		
		public function gotoAndPlay(start:int, end:int = 0, loop:Boolean = false):void {
			_loop = loop;
			playable = true;
			_startFrame = start;
			if (end == 0) {
				_stopFrame = _totalFrame;
			}else {
				_stopFrame = end;
			}
			_currentFrame = _startFrame;
			timerRuning();
		}
		
		public function gotoAndStop(stopAt:int):void {
			_currentFrame = stopAt;
			playable = false;
			timerRuning();
		}
		
	}

}